export function loadImage(url) {
    var _iamge = new Image()
    _iamge.crossOrigin = "Anonymous"
    _iamge.src = url
    return new Promise(resolve => {
        _iamge.onload = () => {
            resolve(_iamge)
        }
    })
}

export function canvas2imageSrc(canvas) {
    return canvas.toDataURL("image/png");
}

export async function mergerImage(productImageSrc, designImageSrc) {
    var dom = document.createElement('canvas')
    var ctx = dom.getContext("2d")
    var fabricImage = await  loadImage(designImageSrc)
    var productImage = await  loadImage(productImageSrc)
    var bili = [fabricImage.width / productImage.width, fabricImage.height / productImage.height]
    var finallShowSize = {width: 0, height: 0};
    if (productImage.width > productImage.height) {
        finallShowSize = {width: productImage.width * bili[0], height: productImage.height * bili[0]}
    } else {
        finallShowSize = {width: productImage.width * bili[1], height: productImage.height * bili[1]}
    }
    dom.width = finallShowSize.width
    dom.height = finallShowSize.height
    ctx.drawImage(fabricImage, 0, 0);
    ctx.drawImage(productImage, 0, 0, finallShowSize.width, finallShowSize.height);
    var finalImageSrc = canvas2imageSrc(dom)
    return finalImageSrc
}

